const Like = require('../models/Like');
const Article = require('../models/Article');

// 获取文章点赞数和当前用户点赞状态
exports.getLikes = async (req, res) => {
  try {
    const articleId = req.params.id;
    const userId = req.user ? req.user._id : null;

    // 获取文章
    const article = await Article.findById(articleId).populate('likeCount');
    
    if (!article) {
      return res.status(404).json({ success: false, message: '文章不存在' });
    }

    // 检查当前用户是否已点赞
    let isLikedByCurrentUser = false;
    if (userId) {
      const existingLike = await Like.findOne({
        article: articleId,
        user: userId
      });
      isLikedByCurrentUser = !!existingLike;
    }

    // 获取点赞总数
    const likeCount = await Like.countDocuments({ article: articleId });

    res.json({
      success: true,
      like_count: likeCount,
      is_liked_by_current_user: isLikedByCurrentUser
    });
  } catch (error) {
    console.error('获取点赞信息失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
};

// 处理点赞或取消点赞
exports.toggleLike = async (req, res) => {
  try {
    const articleId = req.params.id;
    const userId = req.user ? req.user._id : null;
    const { action } = req.body;

    if (!userId) {
      return res.status(401).json({ success: false, message: '请先登录' });
    }

    // 检查文章是否存在
    const article = await Article.findById(articleId);
    if (!article) {
      return res.status(404).json({ success: false, message: '文章不存在' });
    }

    // 处理点赞或取消点赞
    if (action === 'like') {
      // 添加点赞（如果已存在则忽略）
      try {
        await Like.create({
          article: articleId,
          user: userId
        });
      } catch (err) {
        // 如果是因为唯一索引约束导致的错误，可以忽略
        if (err.code !== 11000) {
          throw err;
        }
      }
    } else if (action === 'unlike') {
      // 取消点赞
      await Like.findOneAndDelete({
        article: articleId,
        user: userId
      });
    }

    // 获取更新后的点赞总数
    const likeCount = await Like.countDocuments({ article: articleId });

    res.json({
      success: true,
      like_count: likeCount,
      is_liked_by_current_user: action === 'like'
    });
  } catch (error) {
    console.error('点赞操作失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
}; 